import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'

import NavLink from './NavLink'
import TextInput from './TextInput'
import SelectInput from './SelectInput'
import Table from './Table'
import {tmToFormatTime} from './../publicAPI/commonF'
import {ROOTPATH, myAjax, ROOTURL, myAjaxJson, myAjaxGet, getAuthShop} from './../publicAPI/publicAPI'

class OrderM extends Component {
	//初始化
	constructor (props, context) {
	    super(props, context)
	    var _rWapperHeigh = window.innerHeight;
	   	//console.log(ROOTPATH)
	    this.state = {
	    	isCheck: false,
	    	rHeight: _rWapperHeigh,
	    	select_show: "none",
	    	InputValue: "",      //所选门店名字
	    	shops: [{id: undefined, dname: "全部"}],           //用于显示
	    	filterShops: {},    //用于订单中查询对应的门店
	    	filterBarbers: {},   //用于订单中搜索对应的理发师

	    	barbers: [{id: 500, meta: {name: "全部"}}],         //每个门店对应的理发师
	    	service: [],        //门店对应的服务类型
	    	orders: [],         //订单
	    	isShowTKBtn: "none",  //是否显示退款按钮
	    	isShowLoading: "none" //是否显示加载gif

	    } // 初始化状态

	    this.shop = {};//当前选择门店
	    this.requestParam = {};    //请求参数
	    this.start = 0; //从第几条获取订单
	    this.limit = 10; //每页显示订单数目
	    this.requestAll = false; //判断是否请求所有数据
	    this.customers = {} //存储客户信息


	    //this.agreeRefund(223)
	}

	componentWillMount() {
		//console.log("将安装");
	}

	componentDidMount() {
	    //console.log("安装成功");

	    //获得门店信息
		const newUrl = ROOTURL + 'shop/search.api';
		var shops = {};

		// myAjaxJson(newUrl, 'POST', {
	  //       where:{
	  //           dd: [
	  //               ["eq",false]
	  //           ],
		// 		"order":[
	  //              ["id", "asc"]
	  //            ],
	  //     }}, (data) => {
		// 	console.log(data)
		// 	data.map((item, index) => {
		// 		shops[item.id] = {
		// 			id: item.id,
		// 			dname: item.dname
		// 		}
		// 	})
		// 	let shopsL = this.state.shops.concat(data)
		// 	sessionStorage.setItem("filterShops", JSON.stringify(shops))
		// 	console.log(shopsL)
		// 	this.setState({shops: shopsL, filterShops: shops})
		// }, (data) => {
		// 	console.log('failure'+ data)
		// });
    getAuthShop({
				"order":[
             ["id", "asc"]
           ],
	      }, (data) => {
						data.map((item, index) => {
								shops[item.id] = {
									id: item.id,
									dname: item.dname
								}
						})
						let shopsL = this.state.shops.concat(data)
						sessionStorage.setItem("filterShops", JSON.stringify(shops))
						this.setState({shops: shopsL, filterShops: shops})
		  })

		this.selectContracts = []

		//获取订单数
		this.getOrders();
		//获取所有理发师
		this.getAllBabers();


	}

	//获取订单数据
	getOrders() {
		this.setState({isShowLoading: "block"})
		//订单
	    const orderUrl = ROOTURL + 'contract/search.api';
	    const self = this;
	    const params = this.requestParam
	    myAjaxJson(orderUrl, 'POST', {
				    	where: params,
				    	"order":[["id", "desc"]],
				    	start: self.start,
				    	limit: self.limit
				    }, (data) => {
				    	if(data.length < self.limit) {
				    		self.requestAll = true
				    	} else {self.requestAll = false}
				    	self.setState({orders: data, isShowLoading: "none"})

				    }, (data) => {
				    	alert("加载订单失败，请刷新重试！")
				    	this.setState({isShowLoading: "none"})
				    })
	}

	//获取所有理发师
	getAllBabers() {
		const newUrl= ROOTURL + 'servant/profile/search.api';
		var allBarbers = JSON.parse(sessionStorage.getItem("allBarbers"));
		if(allBarbers) {
			this.setState({filterBarbers: allBarbers})

		} else {
			var allBarbers = {}
			myAjaxJson(newUrl, 'POST', {
				start: 0,
				limit: 1000
			}, (data) => {
				data.map((item, index) => {
					allBarbers[item.id] = {
						id: item.id,
						name: item.meta.name
					}
				})
				sessionStorage.setItem("allBarbers", JSON.stringify(allBarbers))
				this.setState({filterBarbers: allBarbers})
			}, (data) => {
				alert("获取理发师失败")
				this.getAllBabers()
			})
		}
	}

	//获取订单中的客户
	getCustomer(id, index) {
		const newUrl= ROOTURL + 'customer/profile/search.api';
		const self = this
		if(!this.customers[id]) {
			myAjaxJson(newUrl, 'POST', {
				where: {
					id: [["eq", id]]
				}
			}, (data) => {
				self.customers[id] = data[0] ? data[0].dname : ''
				self.refs["order-"+id+"-"+index].innerHTML = data[0] ? data[0].dname : ''

			}, (data) => {
				console.log('failure', data)
			})
		}
	}

	//翻页按钮
	handlePageClick(e) {//1为下一页，2为上一页
		const _buttonValue = e.target.value

		if(_buttonValue == 1) {
			this.start = this.start + this.limit -1

		} else {
			this.start = this.start - this.limit + 1
		}
		this.getOrders()
	}

	//复选框
	handleSelect(e) {
		let cId = e.target.value
		let isChecked = e.target.checked

		if(e.target.checked) {
			this.selectContracts.push(cId)
		} else {
			let index = this.selectContracts.indexOf(cId)
			if(index > -1) this.selectContracts.splice(index, 1)
		}
	}
	//点击复选框
	// checkBoxClick(e) {
	// 	console.log(e)
	// }

	//下拉框
	selectChange(e, type="shopId") {
		this.start = 0; //从第几条获取订单

		const self = this;

		this.requestParam = Object.assign({}, self.requestParam,  {[type]: [["eq", e]], stServe: [['eq', false]], stRate: [['eq', false]]})
		//alert(e)
		if(e == 500) {
			this.requestParam = Object.assign({}, self.requestParam,  {[type]: undefined,stServe: [['eq', false]], stRate: [['eq', false]]})
		}
		else {
			this.requestParam = Object.assign({}, self.requestParam,  {[type]: [["eq", e]]})
		}


		if(type == "stPayment" && e == 1000) {
			this.requestParam = Object.assign({}, self.requestParam,  {[type]: undefined, stServe: [['eq', true]]})
		}

		if(type == "stPayment" && e == 2000) {
			this.requestParam = Object.assign({}, self.requestParam,  {[type]: undefined, stRate: [['eq', true]],stServe: [['eq', true]]})
		}

		if(e == -80 && type == "stPayment") {
			this.setState({isShowTKBtn: "block"})
		} else {
			this.setState({isShowTKBtn: "none"})
		}
		this.getOrders()
	}

	inputFocus() {
		this.setState({select_show: "block"})
	}

	//选择门店，获取理发师
	inputTClick(e) {
		const selectValue = e.target.value
		const selectTxt = e.target.innerHTML
		const self = this

		this.start = 0
		this.requestAll = false
		this.shop.id = selectValue

		if(!selectValue) {
			this.requestParam = Object.assign({}, self.requestParam,  {shopId: undefined})
		} else {
			this.requestParam = Object.assign({}, self.requestParam,  {shopId: [["eq", selectValue]]})
		}

		this.getOrders()

		this.getService()
		this.getBaberOption()
		this.setState({select_show: "none", InputValue: selectTxt})
	}

	//获取当前所选门店服务类型
	getService() {
		const newUrl= ROOTURL + 'serv/shop/search.api';
		const shop = this.shop;
		const data = {
			where: {
				dd:[
	                ["eq", false]
	            ],
	            shopId: [
	                ["eq", shop.id]
	            ]
			}
		}

	    if (sessionStorage.getItem("services" + shop.id)) {
           this.setState({
             service: JSON.parse(sessionStorage.getItem("services" + shop.id))
           })
           return false;
        }
		myAjaxJson(newUrl, 'POST', data, (data) => {
			const services = [];
            if (data.length > 0){
                data.forEach(function(server) {
                     services.push({
                         id: server.id,
                         dname: server.meta.prototypeServiceName
                     });
                })
            } else {
                //alert("请先为门店设置服务类型")
            }
            sessionStorage.setItem("services"+shop.id, JSON.stringify(services));
			this.setState({service: services});
		}, (data) => {
			//alert("获取服务类型失败")
		})
	}


	//理发师列表
	getBaberOption() {

		const newUrl= ROOTURL + 'servant/profile/search.api';
		const shop = this.shop;
		const _data = {
			where: {
	            shopId: [
	                ["eq", shop.id]
	            ]
			}
		}

	    if (sessionStorage.getItem("barbers" + shop.id)) {
	    	let babersL = this.state.barbers.concat(JSON.parse(sessionStorage.getItem("barbers" + shop.id)))
           this.setState({
             barbers: babersL
           })
           return false;
        }
		myAjaxJson(newUrl, 'POST', _data, (data) => {
            if (data.length < 0) {
                //alert("门店没有分配理发师")
            }
            sessionStorage.setItem("barbers"+shop.id, JSON.stringify(data));
            let babersL = this.state.barbers.concat(data)
			this.setState({barbers: babersL});
		}, (data) => {
			//alert("获取理发师失败")
		})

	}


	//同意退款
	agreeRefund() {
		this.setState({isShowLoading: "block"})
		const newUrl = ROOTURL + 'contract/refund.api';
		let selectL = this.selectContracts.length
		for(let i = 0; i < selectL; i++) {
			let _id = this.selectContracts[i]

			let _data = {
				contractId: _id,
				fullRefund : true
			}

			myAjax(newUrl, 'POST', _data, (data) => {
				this.sureAgreeRefund(_id, i === selectL - 1)
				//console.log(i === selectL - 1)
			}, (data) => {
				alert("订单"+_id+"同意退款失败")
				if(i === selectL - 1) {
					location.reload();
				}
				console.log(data)
			});
		}

	}

	//确认同意退款
	sureAgreeRefund(cId, flagSelectL) {
		const newUrl = ROOTURL + 'contract/submit-refund.api';
		let _data = {
			contractId: cId,
		}
		myAjax(newUrl, 'POST', _data, (data) => {
			this.forceSync(cId,flagSelectL)
		}, (data) => {
			alert("订单"+cId+"同意退款失败")
		});
	}
	//强制同步
  forceSync(cId, flagSelectL) {
		const newUrl = ROOTURL + 'contract/payment/query.api';
		let _data = {
			contractId: cId,
			forceSync: true
		}
		myAjaxGet(newUrl, _data, (data) => {
			if(flagSelectL) {
				location.reload();
			}
		}, (data) => {
			alert("订单"+cId+"状态同步失败")
		});
	}

	//拒绝退款
	refuseRefund() {
		this.setState({isShowLoading: "block"})
		const newUrl = ROOTURL + 'contract/reject-refund.api';
		let selectL = this.selectContracts.length
		for(let i = 0; i < selectL; i++) {
			let _id = this.selectContracts[i]
			let _data = {
				contractId: _id,
			}
			myAjax(newUrl, 'POST', _data, (data) => {
				if(i === selectL - 1) location.reload();
			}, (data) => {

				alert("订单"+cId+"拒绝退款失败")
				if(i === selectL - 1) location.reload();
			});
		}
	}


	//render thead
	tHead() {
		var data = [
				{name: "订单号"},
				{name: "客户姓名"},
				{name: "交易门店"},
				{name: "交易理发师"},
				{name: "订单价格"},
				{name: "实付金额"},
				{name: "交易状态"},
				{name: "服务时间"},
				{name: "操作"}
			]
		const _headArr = []
		const _width = {
			"0" : "8%",
			"1" : "14%",
			"2" : "15%",
			"3" : "10%",
			"4" : "10%",
			"5" : "8%",
			"6" : "10%",
			"7" : "10%",
			"8" : "11"
		}
		_headArr.push(<th style={{width:'5%'}} role="1" key='' onClick={(e) => this.handleSelect(e)}></th>)
		_headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1" key={index}>{item.name}</th>))
		return _headArr;
	}

	//render tbody
	tBody(data) {
		const _state = {
			'-128': "未及时支付",
			'-96': "未及时到店服务",
			'0': "待支付",
			'16': "已支付",
			'-80': "申请退款",
			'-79': "已退款",
			'-78': "拒绝退款",
			'-64': "支付异常",
			'-112': "未及时到店服务"
		};
		const self = this

		return data.map((item, index) => {
							let status = item.stServe ? "已服务" : _state[item.stPayment];
							if(item.stServe) {
							 	status = "已服务";
							 	if(item.stRate) status = "已评价";
							}
							return	(<tr key={index}>
										<td><input type="checkbox" value={item.id} style={this.props.style}
													className={this.props.checkboxClass ? this.props.checkboxClass : "default-checkbox "}
													onChange={(e) => this.handleSelect(e)}/>
										</td>
										<td>{item.id}</td>
										<td ref={"order-" + item.customerId + "-" +index}>{self.customers[item.customerId] == undefined ? this.getCustomer(item.customerId, index) : self.customers[item.customerId]}</td>
										<td>{this.state.filterShops[item.shopId] ? this.state.filterShops[item.shopId].dname : ''}</td>
										<td>{this.state.filterBarbers[item.servantId] ? this.state.filterBarbers[item.servantId].name : ''}</td>
										<td>{item.grossPay}</td>
										<td>{item.netPay}</td>
										<td>{status}</td>
										<td>{item.tmServe ? tmToFormatTime(item.tmServe) : ''}</td>
										<td><NavLink  to={ROOTPATH+`/OrderM/${item.id}`} className="rbtn green">查看</NavLink></td>
									</tr>)})
	}

    render() {

	    return (
	    	<div className="right-wapper" style={{height: this.state.rHeight}}>
	    		<div className="loading-wapper" style={{display: this.state.isShowLoading}}><img src={require('./../imgs/loading.gif')} alt=""/></div>
	    		<div className="rt-wrap rt-wrap-header">
	    			<div className="input-div pr">
		    			<label>门店：</label>
		    			<input type="text" placeholder="请选择门店" className="default-text"
		    				value={this.state.InputValue}
		    				onFocus={() => this.inputFocus()}/>
		    			<ul className="input_select" style={{display: this.state.select_show}}>
		    				{this.state.shops.map((item, index) => <li onClick={(e) => this.inputTClick(e)} key={index} value={item.id}>{item.dname}</li>)}
		    			</ul>
		    		</div>
		    		<div className="input-div">
		    			<label>理发师：</label>
		    			<SelectInput
		    						optionsData={this.state.barbers.map((item, index) => <option value={item.id} key={index} onClick={(e) => this.selectChange(e)}>{item.meta.name}</option>)}
		    						onChange={(e) => this.selectChange(e, "servantId")}/>
		    		</div>
		    		<div className="input-div">
		    			<label>状态：</label>
		    			<SelectInput
		    						optionsData={
		    							[
		    								{stateName: "全部", type: 500},
		    								{stateName: "订单超时未支付", type: -128},
		    								{stateName: "订单未及时去店服务", type: -112},
		    								{stateName: "订单支付异常", type: -64},
		    								{stateName: "未支付", type: 0},
		    								{stateName: "已支付", type: 16},
		    								{stateName: "申请退款", type: -80},
		    								{stateName: "已退款", type: -79},
		    								{stateName: "拒绝退款", type: -78},
		    								{stateName: "已接受服务", type: 1000},
		    								{stateName: "已评价", type: 2000}
		    							].map((item, index) => <option value={item.type} key={index} onClick={(e) => this.selectChange(e)}>{item.stateName}</option>)
		    						}
		    						onChange={(e) => this.selectChange(e, "stPayment")} />
		    		</div>
		    		<div className="input-div">
		    			<label>服务类型</label>
		    			<SelectInput
		    						optionsData={this.state.service.map((item, index) => <option value={item.id} key={index} onClick={(e) => this.selectChange(e)}>{item.dname}</option>)}
		    						onChange={(e) => this.selectChange(e, "servTypeId")} />
		    		</div>
		    		<div style={{display: this.state.isShowTKBtn}}>
		    			<button className={"info-btn"} onClick={() => this.agreeRefund()}>退款</button>
						<button className={"info-btn"} onClick={() => this.refuseRefund()}>拒绝退款</button>
		    		</div>
	    		</div>

	    		<div className="rt-wrap">
	    			<h3 className="catagory">
	    				<span className="cata-title">订单管理</span>
	    				<button className="next" value="1" style={{display: this.requestAll ? "none" : "block"}} onClick={(e) => this.handlePageClick(e)}></button>
	    				<button className="prev" value="2" style={{display: this.start ? "block" : "none"}} onClick={(e) => this.handlePageClick(e)}></button>
	    			</h3>
	    			<Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)(this.state.orders)}/>
	    		</div>

	    	</div>
	    )
	  }
}

export default OrderM
